package com.mbbb.yygh.gateway.config;

import com.google.gson.JsonObject;
import com.mbbb.yygh.common.utils.JwtHelper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

//自定义过滤器，登录校验
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    //通过网关发送请求，首先执行filter
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //请求对象获取请求路径
        String path = request.getURI().getPath();
        //判断路径是否需要登录
        // /api/order/ 进行登录判断
        if(antPathMatcher.match("/api/order/**", path)) {
            //在header有token字符串
            List<String> tokenList = request.getHeaders().get("token");
            //判断token是否取到
            if(tokenList == null) { //没有token，没有登录
                //返回没有登录提示数据，弹出框
                ServerHttpResponse response = exchange.getResponse();
                return out(response);
            } else { //有token
                //判断token是否有效
                boolean isExpire = JwtHelper.isExpiration(tokenList.get(0));
                if(isExpire) { //true 无效token
                    //返回需要登录提示，弹出框
                    ServerHttpResponse response = exchange.getResponse();
                    return out(response);
                }
            }
        }
        //放行
        return chain.filter(exchange);
    }

    //过滤器执行优先级
    @Override
    public int getOrder() {
        return 0;
    }

    //返回信息
    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}

